package com.ktjy.cond;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;
import java.util.Map;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ConditionOnPropertyEnable {
    //当配置中对应属性值为true时,则需要创建bean
    String enableProperty();

    /**
     * 实现了Condition接口,可以判断是否需要注册被标注的Bean
     */
    //接口内部的类默认是 public 和 static 的
    class OnEnableCondition implements Condition {
        private static final Logger LOGGER = LoggerFactory.getLogger(OnEnableCondition.class);

        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            //获取元数据中被标记的@ConditionOnPropertyEnable注解的所有配置值
            Map<String, Object> attrs = metadata.getAnnotationAttributes(ConditionOnPropertyEnable.class.getName());
            //获取到注解定义的enableProperty的值
            String enableProperty = (String) attrs.get("enableProperty");
            /**
             * 自己理解:metadata->获取这个类某个注解中某个属性的值(例如:a),然后context->获取环境变量中对应属性(a)的值,然后返回true/false
             * ture 注册Bean false 不注册Bean
             */
            LOGGER.info("当前读取到属性名称enableProperty={}", enableProperty);
            //从环境中获取property文件对应配置的属性值
            String propertyValue = context.getEnvironment().getProperty(enableProperty);
            LOGGER.info("当前读取到属性值{}={}", enableProperty, propertyValue);
            //是否需要注册
            Boolean needRegister = Boolean.valueOf(propertyValue);
            LOGGER.info("标准的Bean是否需要注册:{}", needRegister);
            return needRegister;
        }
    }
}
